<template>
	<div class="pound-container">
		<div class="pound-bottom">
			<el-card>
				<template #header>
					<div style="display: flex;justify-content: space-between;">
						<div class="card-header" style="font-size: 24px;font-weight: 550;">
							<span>过磅计划列表</span>
						</div>
						<div>
							<el-dropdown placement="bottom-end">
								<el-icon :size="28">
									<Plus />
								</el-icon>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item command="addSingle" icon="CirclePlusFilled" @click="newlist">
											新增过磅计划
										</el-dropdown-item>
										<el-dropdown-item command="addBatch" icon="Files" @click="openBatchDialog">
											批量新增过磅计划
										</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
						</div>
					</div>
				</template>
				
				<div class="search-form" style="margin-bottom: 16px; display: flex; gap: 16px; align-items: center;">
					<!-- 车牌号检索 -->
					<el-form-item label="车牌号" style="margin-bottom: 0;">
						<el-input 
							v-model="searchParams.autoLicense" 
							placeholder="请输入车牌号" 
							style="width: 180px;"
							@keyup.enter="fetchData()"  
						/>
					</el-form-item>
			
					<!-- 货物名称检索 -->
					<el-form-item label="货物名称" style="margin-bottom: 0;">
						
				<el-input
					v-model="searchParams.cargoName" 
					placeholder="请输入货物名称" 
					style="width: 180px;"
					
				/>
					</el-form-item>
			
					<!-- 发货单位检索 -->
					<el-form-item label="发货单位" style="margin-bottom: 0;">
						<el-select 
							v-model="searchParams.shippingCompanyId" 
							placeholder="请选择发货单位" 
							style="width: 180px;"
							filterable
							clearable
							@change="handleSelectChange"
						>
							<el-option 
								v-for="item in caiOptions" 
								:key="item.id" 
								:label="item.companyName" 
								:value="item.id" 
							/>
						</el-select>
					</el-form-item>
			
					<!-- 收货单位检索 -->
					<el-form-item label="收货单位" style="margin-bottom: 0;">
						<el-select 
							v-model="searchParams.receivingCompanyId" 
							placeholder="请选择收货单位" 
							style="width: 180px;"
							filterable
							clearable
							@change="handleSelectChange"
						>
							<el-option 
								v-for="item in xiaoOptions" 
								:key="item.id" 
								:label="item.companyName" 
								:value="item.id" 
							/>
						</el-select>
					</el-form-item>
			
					<!-- 检索按钮 -->
					<el-button type="primary" @click="fetchData()">查询</el-button>
			
					<!-- 重置按钮 -->
					<el-button @click="resetSearch()">重置</el-button>
				</div>
				
				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="createTime" label="创建时间" width="200" />
					<el-table-column prop="autoLicense" label="车牌号" width="120" />
					<el-table-column prop="cargoName" label="货物名称" />
					<el-table-column prop="specifications" label="规格" />
					<el-table-column prop="shippingCompany" label="发货厂家" />
					<el-table-column prop="receivingCompany" label="收货厂家" />
					<el-table-column prop="driverName" label="司机姓名" />
					<el-table-column prop="weighingType" label="过磅类型">
						<template #default="{row}">
							<span>{{ row.weighingType === 1 ? '采购' : '销售' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="150" fixed="right">
						<template #default="scope">
							<el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div style="margin-top: 5px; display: flex;flex-direction:row-reverse;">
					<el-pagination v-if="total>0" v-model:current-page="listQuery.current"
						v-model:page-size="listQuery.size" :page-sizes="[5, 8, 10]" :size="size" :background="false"
						layout="sizes, prev, pager, next" :total="total" @size-change="handleSizeChange"
						@current-change="handleCurrentChange" />
				</div>
			</el-card>
		</div>
	</div>

	<el-dialog v-model="dialogVisible" title="新增过磅计划" width="50%">
		<el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
			<el-form-item label="过磅类型" prop="weighingType">
				<el-select style="width: 180px" v-model="formData.weighingType" placeholder="请选择过磅类型" clearable>
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item label="车牌号" prop="autoLicense">
				<el-input v-model="formData.autoLicense" placeholder="请输入车牌号" style="width: 180px;"
					@input="formData.autoLicense = formData.autoLicense.toUpperCase()" />
			</el-form-item>

			<el-form-item label="货物名称" prop="cargoName">
				<el-select v-model="formData.cargoName" filterable allow-create default-first-option
					:reserve-keyword="false" placeholder="请输入或选择货物名称" style="width: 180px"
					@change="(val) => handleCargoChange(val, formData)" value-key="id">
					<el-option v-for="item in cargoOptions" :key="item.cargoName" :label="item.cargoName"
						:value="item.cargoName">
						<span style="float: left">{{ item.cargoName }}</span>
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="规格">
				<el-input v-model="formData.specifications" placeholder="请输入规格" style="width: 180px;" />
			</el-form-item>

			<el-form-item label="发货厂家" prop="shippingCompanyId">
				<el-select v-model="formData.shippingCompanyId" filterable default-first-option
					:reserve-keyword="false" placeholder="请选择发货厂家" style="width: 180px" value-key="id">
					<el-option v-for="item in caiOptions" :key="item.id" :label="item.companyName" :value="item.id">
						<span>{{ item.companyName }}</span>
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="收货厂家" prop="receivingCompanyId">
				<el-select v-model="formData.receivingCompanyId" filterable default-first-option
					:reserve-keyword="false" placeholder="请选择收货厂家" style="width: 180px" value-key="id">
					<el-option v-for="item in xiaoOptions" :key="item.id" :label="item.companyName" :value="item.id">
						<span>{{ item.companyName }}</span>
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item label="司机姓名">
				<el-input v-model="formData.driverName" placeholder="请输入司机姓名" style="width: 180px;" />
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="resetForm(formRef)">取消</el-button>
			<el-button type="primary" @click="handleSubmit">确定</el-button>
		</template>
	</el-dialog>
	
	<!-- 批量新增过磅计划弹窗 -->
	<el-dialog v-model="batchDialogVisible" title="批量新增过磅计划" width="85%" :before-close="resetBatchForm">
		<div style="display: flex; gap: 24px; margin-bottom: 20px;">
			<div style="flex: 0 0 45%;">
				<el-form ref="batchFormRef" :model="batchFormData" :rules="batchRules" label-width="120px">
					<el-form-item label="过磅类型" prop="weighingType" style="margin-bottom: 16px;">
						<el-select 
							style="width: 100%;" 
							v-model="batchFormData.weighingType" 
							placeholder="请选择过磅类型" 
							required
						>
							<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
					</el-form-item>
	
					<el-form-item label="车牌号" prop="licenseText" style="margin-bottom: 16px;">
						<el-input
							type="textarea"
							v-model="batchFormData.licenseText"
							placeholder="示例：冀AFQ981粤A8850Y陕ATH793冀A5C722"
							rows="4"
							style="width: 100%; border-radius: 4px;"
							@input="handleLicenseTextChange"
						/>
						<div style="margin-top: 8px; color: #666; font-size: 12px; line-height: 1.4;">
							提示：系统以汉字（如冀、粤、陕）为分隔符自动识别，无需手动换行
						</div>
					</el-form-item>
	
					<el-form-item label="货物名称" prop="cargoName" style="margin-bottom: 16px;">
						<el-select 
							v-model="batchFormData.cargoName" 
							filterable 
							allow-create 
							default-first-option
							:reserve-keyword="false" 
							placeholder="请选择/输入货物名称" 
							style="width: 100%;"
							@change="(val) => handleBatchCargoChange(val)"
						>
							<el-option 
								v-for="item in cargoOptions" 
								:key="item.cargoName" 
								:label="item.cargoName" 
								:value="item.cargoName"
							>
								{{ item.cargoName }}
							</el-option>
						</el-select>
					</el-form-item>
	
					<el-form-item label="规格" prop="specifications" style="margin-bottom: 16px;">
						<el-input 
							v-model="batchFormData.specifications" 
							placeholder="请输入规格" 
							style="width: 100%;" 
						/>
					</el-form-item>
	
					<el-form-item label="发货厂家" prop="shippingCompanyId" style="margin-bottom: 16px;">
						<el-select 
							v-model="batchFormData.shippingCompanyId" 
							filterable 
							default-first-option
							:reserve-keyword="false" 
							placeholder="请选择发货厂家" 
							style="width: 100%;"
						>
							<el-option 
								v-for="item in caiOptions" 
								:key="item.id" 
								:label="item.companyName" 
								:value="item.id"
							>
								{{ item.companyName }}
							</el-option>
						</el-select>
					</el-form-item>
	
					<el-form-item label="收货厂家" prop="receivingCompanyId" style="margin-bottom: 16px;">
						<el-select 
							v-model="batchFormData.receivingCompanyId" 
							filterable 
							default-first-option
							:reserve-keyword="false" 
							placeholder="请选择收货厂家" 
							style="width: 100%;"
						>
							<el-option 
								v-for="item in xiaoOptions" 
								:key="item.id" 
								:label="item.companyName" 
								:value="item.id"
							>
								{{ item.companyName }}
							</el-option>
						</el-select>
					</el-form-item>
	
					<el-form-item label="司机姓名" style="margin-bottom: 0;">
						<el-input 
							v-model="batchFormData.driverName" 
							placeholder="可选：统一填写司机姓名" 
							style="width: 100%;" 
						/>
					</el-form-item>
				</el-form>
			</div>
	
			<div style="flex: 0 0 50%;">
				<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
					<h3 style="font-size: 16px; font-weight: 500; color: #1f2937; margin: 0;">
						识别结果（共 {{ batchLicenseList.length }} 个）
					</h3>
					<el-button 
						type="text" 
						size="small" 
						@click="clearAllLicenses"
						:disabled="batchLicenseList.length === 0"
						style="color: #ef4444; padding: 4px 0;"
					>
						清空
					</el-button>
				</div>
				<!-- size="small" -->
				<el-table 
					:data="batchLicenseList" 
					border 
					style="width: 100%; border-radius: 4px; overflow: hidden;" 
					:height="batchLicenseList.length>0?450:180" 
				>
					<el-table-column label="序号" type="index" width="60" align="center" />
					<el-table-column label="车牌号" prop="autoLicense" align="center" min-width="120">
						<template #default="{ row }">
							<span :style="row.isValid ? 'color: #1f2937;' : 'color: #ef4444; font-weight: 400;'">
								{{ row.autoLicense || '无效格式' }}
							</span>
						</template>
					</el-table-column>
					<el-table-column label="状态" align="center" width="100">
						<template #default="{ row }">
							<el-tag :type="row.isValid ? 'success' : 'danger'" size="small" effect="plain">
								{{ row.isValid ? '有效' : '无效' }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" width="80">
						<template #default="{ $index }">
							<el-button 
								link 
								type="danger" 
								size="small" 
								@click="deleteSingleLicense($index)"
								style="padding: 4px 0;"
							>
								删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>
	
				<div v-if="batchLicenseList.length === 0" style="text-align: center; padding: 60px 0; color: #6b7280; border: 1px solid #e5e7eb; border-radius: 4px; margin-top: 1px;">
					<el-empty description="请在左侧输入车牌号，系统将自动识别" size="small" />
				</div>
			</div>
		</div>
	
		<template #footer>
			<el-button @click="resetBatchForm()">取消</el-button>
			<el-button 
				type="primary" 
				@click="handleBatchSubmit"
				:disabled="batchLicenseList.filter(item => item.isValid).length === 0"
			>
				批量提交（{{ batchLicenseList.filter(item => item.isValid).length }} 个有效车牌）
			</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import {
	ref,
	reactive,
	onMounted,
	onBeforeUnmount,
	getCurrentInstance,
	nextTick
} from 'vue';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';

const size = ref<ComponentSize>('default');
const { proxy } = getCurrentInstance();
const router = useRouter();
const dialogVisible = ref(false);
const formRef = ref<FormInstance>();
const options = [
	{ label: '采购', value: 1 },
	{ label: '销售', value: 2 }
];

// 表单数据
const formData = reactive({
	autoLicense: '',
	cargoName: '',
	specifications: '',
	shippingCompanyId: '',
	receivingCompanyId: '',
	driverName: '',
	deductingId: '',
	weighingType: 1
});

// 类型定义
interface CargoOption {
	cargoName: string;
	id: string;
	specifications?: string;
}

interface CompanyOption {
	companyName: string;
	id: string;
}

// 下拉选项数据
const cargoOptions = ref<CargoOption[]>([]);
const caiOptions = ref<CompanyOption[]>([]);
const xiaoOptions = ref<CompanyOption[]>([]);

// 批量新增相关
const batchDialogVisible = ref(false);
const batchFormRef = ref<FormInstance>();
const batchFormData = reactive({
	licenseText: '',
	cargoName: '',
	specifications: '',
	shippingCompanyId: '',
	receivingCompanyId: '',
	driverName: '',
	weighingType: 1,
	deductingId: ''
});

const batchRules = reactive<FormRules>({
	weighingType: [{ required: true, message: '请选择过磅类型', trigger: 'blur' }],
	licenseText: [
		{ required: true, message: '请输入批量车牌号', trigger: 'blur' },
		{ min: 5, message: '请至少输入1个有效车牌号（如冀A12345）', trigger: 'blur' }
	],
	cargoName: [{ required: true, message: '请选择/输入货物名称', trigger: 'blur' }],
	shippingCompanyId: [{ required: true, message: '请选择发货厂家', trigger: 'blur' }],
	receivingCompanyId: [{ required: true, message: '请选择收货厂家', trigger: 'blur' }]
});

// 车牌号识别结果列表
interface BatchLicenseItem {
	autoLicense: string;
	isValid: boolean;
}
const batchLicenseList = ref<BatchLicenseItem[]>([]);

// 表单验证规则
const rules = reactive<FormRules>({
	autoLicense: [
		{
			required: true,
			message: '请输入车牌号',
			trigger: 'blur'
		},
		{
			pattern: /^(?:[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z](?:(?:(?:[0-9]{5}[DF])|(?:[DF][A-HJ-NP-Z0-9][0-9]{4}))|(?:[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳])))$/,
			message: '车牌号格式不正确',
			trigger: 'blur'
		}
	],
	cargoName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }],
	shippingCompanyId: [{ required: true, message: '请选择发货厂家', trigger: 'blur' }],
	receivingCompanyId: [{ required: true, message: '请选择收货厂家', trigger: 'blur' }]
});

// 重置表单
const resetForm = () => {
	const formEl = formRef.value;
	if (formEl?.resetFields) {
		formEl.resetFields();
		formData.driverName = '';
		formData.specifications = '';
		dialogVisible.value = false;
	} else {
		console.warn('表单实例不可用');
	}
};

// 打开批量新增对话框
const openBatchDialog = () => {
	batchDialogVisible.value = true;
	// resetBatchForm();
};

// 处理车牌号文本变化
const handleLicenseTextChange = () => {
	const licenseText = batchFormData.licenseText.trim();
	if (!licenseText) {
		batchLicenseList.value = [];
		return;
	}
	
	// 正则匹配车牌号
	const licenseReg = /([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z0-9挂学警港澳]{5,10})/g;
	const matchedLicenses = licenseText.match(licenseReg) || [];
	
	// 去重+格式校验
	const uniqueLicenses = Array.from(new Set(matchedLicenses)).map(license => ({
		autoLicense: license.toUpperCase(),
		isValid: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼][A-HJ-NP-Z0-9挂学警港澳]{5,10}$/.test(license)
	}));
	
	// 使用nextTick避免更新冲突
	nextTick(() => {
		batchLicenseList.value = uniqueLicenses;
	});
};

// 处理批量货物选择变化
const handleBatchCargoChange = (val: string) => {
	nextTick(() => {
		const matchingCargo = cargoOptions.value.find(item => item.cargoName === val);
		if (matchingCargo) {
			batchFormData.specifications = matchingCargo.specifications || '';
			batchFormData.deductingId = matchingCargo.id && !/[\u4e00-\u9fa5]/.test(matchingCargo.id) ? matchingCargo.id : '0';
		}
		if (val && !cargoOptions.value.some(item => item.cargoName === val)) {
			// 创建新数组避免直接修改原数组
			cargoOptions.value = [...cargoOptions.value, { cargoName: val, id: val }];
		}
	});
};

// 删除单个车牌号
const deleteSingleLicense = (index: number) => {
	batchLicenseList.value.splice(index, 1);
	batchFormData.licenseText = batchLicenseList.value.map(item => item.autoLicense).join('');
};

// 清空所有车牌号
const clearAllLicenses = () => {
	batchLicenseList.value = [];
	batchFormData.licenseText = '';
};

// 重置批量表单
const resetBatchForm = () => {
	batchDialogVisible.value = false;
	const formEl = batchFormRef.value;
	if (formEl?.resetFields) formEl.resetFields();
	batchLicenseList.value = [];
	batchFormData.driverName = '';
	batchFormData.specifications = '';
	
	
};

// 批量提交
const handleBatchSubmit = async () => {
	try {
		await batchFormRef.value?.validate();
		const validLicenses = batchLicenseList.value
			.filter(item => item.isValid)
			.map(item => item.autoLicense);

		if (validLicenses.length === 0) {
			ElMessage.warning('请至少保留1个有效车牌号');
			return;
		}

		const jsonData = {
			autoLicenseList: validLicenses,
			template: {
				weighingType: batchFormData.weighingType,
				cargoName: batchFormData.cargoName,
				specifications: batchFormData.specifications,
				shippingCompanyId: batchFormData.shippingCompanyId,
				receivingCompanyId: batchFormData.receivingCompanyId,
				driverName: batchFormData.driverName || '',
				deductingId: batchFormData.deductingId || '0'
			}
		};

		const requestParams = {
			bodyParams: jsonData,
			queryParams: {}
		};

		const requestConfig = {
			headers: {
				'Content-Type': 'application/json'
			}
		};

		const res = await proxy.$request.setAllList({
			...requestParams,
			...requestConfig
		});

		if (res?.data?.code === 200) {
			ElMessage.success(res.data.message);
			resetBatchForm();
			batchDialogVisible.value = false;
			fetchData();
		} else {
			ElMessage.error(res?.data?.message || '批量提交失败');
		}

	} catch (error: any) {
		console.error('请求错误:', error);
		ElMessage.error(error.data?.message || '网络异常');
	}
};

// 处理货物选择变化
const handleCargoChange = (val: string, formData: Record<string, any>) => {
	nextTick(() => {
		const matchingCargo = cargoOptions.value.find(
			(cargo) => formData.cargoName === cargo.cargoName
		);

		if (matchingCargo) {
			formData.specifications = matchingCargo.specifications || '';
		}

		if (val && !cargoOptions.value.some(item => item.id === val)) {
			cargoOptions.value = [...cargoOptions.value, {
				cargoName: val,
				id: val
			}];
		}
	});
};

// 提交表单
const handleSubmit = async () => {
	try {
		await formRef.value?.validate();
		
		const matchingCargo = cargoOptions.value.find(
			(cargo) => cargo.cargoName === formData.cargoName
		);
		formData.deductingId = matchingCargo?.id && !/[\u4e00-\u9fa5]/.test(matchingCargo.id) ? matchingCargo.id : '0';

		proxy.$request.setNewPlan(formData).then((res: any) => {
			if (res.data.code === 200) {
				ElMessage.success('新增成功!');
				resetForm(formRef);
				dialogVisible.value = false;
				fetchData();
			} else {
				ElMessage.error(res.data.message);
			}
		}).catch((err: any) => {
			console.log('err', err);
			ElMessage.error('请求错误');
		});

	} catch (error) {
		console.log('表单验证失败:', error);
	}
};

// 暴露方法
defineExpose({
	open: () => {
		dialogVisible.value = true;
		formRef.value?.resetFields();
	}
});

// 删除计划
const handleDelete = (row: any) => {
	ElMessageBox.confirm('确定要删除这条过磅计划吗？', '删除确认', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		try {
			const res = await proxy.$request.deletePlan({ id: row.id });
			if (res.data.code === 200) {
				ElMessage.success('删除成功!');
				fetchData();
			} else {
				ElMessage.error(res.data.message || '删除失败');
			}
		} catch (error) {
			console.error('删除失败:', error);
			ElMessage.error('删除失败，请稍后重试');
		}
	}).catch(() => {
		// 用户取消删除
	});
};

// 新增计划
const newlist = () => {
	dialogVisible.value = true;
};

// 返回
const handleBack = () => {
	router.go(-1);
};

// 表格数据
const tableData = ref([]);

// 搜索参数（独立于分页参数）
const searchParams = reactive({
	autoLicense: '',
	cargoName: '',
	shippingCompanyId: '',
	receivingCompanyId: ''
});

// 分页参数
const listQuery = reactive({
	current: 1,
	size: 5
});

// 总数
const total = ref(0);

// 处理选择器变化（防止频繁请求）
let searchTimeout: number | null = null;
const handleSelectChange = () => {
	if (searchTimeout) {
		window.clearTimeout(searchTimeout);
	}
	// 延迟300ms执行，避免选择过程中频繁请求
	searchTimeout = window.setTimeout(() => {
		listQuery.current = 1; // 重置到第一页
		fetchData();
	}, 300);
};

// 重置搜索
const resetSearch = () => {
	// 清空搜索参数
	searchParams.autoLicense = '';
	searchParams.cargoName = '';
	searchParams.shippingCompanyId = '';
	searchParams.receivingCompanyId = '';
	
	// 重置分页
	listQuery.current = 1;
	
	// 重新加载
	fetchData();
};

// 获取数据
const fetchData = async () => {
	try {
		// 合并参数但不修改原响应式对象
		const queryParams = {
			...listQuery,
			...searchParams
		};

		const res = await proxy.$request.getPlanList(queryParams);

		if (res?.data?.code === 200) {
			tableData.value = res.data.result?.resultData || [];
			total.value = res.data.result?.totalRows || 0;
		} else {
			ElMessage.error(res?.data?.message || '请求失败');
		}
	} catch (error: any) {
		console.error('API请求错误:', error);
		ElMessage.error(error.message || '网络请求异常');
	}
};

// 获取货物列表
const getCargoNameList = async () => {
	try {
		const res = await proxy.$request.getCargoNameList();
		cargoOptions.value = [];
		if (res?.data?.code === 200 && res.data.result) {
			cargoOptions.value = res.data.result;
		} else {
			ElMessage.error(res?.data?.message || '请求失败');
		}
	} catch (error: any) {
		console.error('API请求错误:', error);
		ElMessage.error(error.message || '网络请求异常');
	}
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
	listQuery.size = val;
	fetchData();
};

// 处理页码变化
const handleCurrentChange = (val: number) => {
	listQuery.current = val;
	fetchData();
};

// 获取公司列表
const getCompanyNameList = async (num: number) => {
	try {
		const res = await proxy.$request.getCompanySelect({ companyType: num });
		if (res?.data?.code === 200 && res.data.result) {
			if (num === 1) {
				caiOptions.value = res.data.result;
			}
			if (num === 2) {
				xiaoOptions.value = res.data.result;
			}
		} else {
			ElMessage.error(res?.data?.message || '请求失败');
		}
	} catch (error: any) {
		console.error('API请求错误:', error);
		ElMessage.error(error.message || '网络请求异常');
	}
};

// 挂载时初始化
onMounted(async () => {
	await Promise.all([
		fetchData(),
		getCargoNameList(),
		getCompanyNameList(1),
		getCompanyNameList(2)
	]);
});

// 卸载前清理
onBeforeUnmount(() => {
	if (searchTimeout) {
		window.clearTimeout(searchTimeout);
	}
});
</script>

<style lang="scss" scoped>
	.pound-container {
		padding: 28px;
		box-sizing: border-box;
		position: relative;

		.pound-bottom {
			width: 100%;
			margin-top: 50px;
		}
	}
</style>
